package user

import (
	"enjoy_xxz/formdata"
	"enjoy_xxz/internal/model/database/redis"
	"enjoy_xxz/internal/model/user"
	"enjoy_xxz/pkg"
	"errors"
	"fmt"
	"gorm.io/gorm"
	"strconv"
)

// 登录
func Login(data formdata.UserLogin) (formdata.UserInfo, error) {
	u := user.User{
		Phone: data.Phone,
	}
	//查询用户手机号是否存在
	detail, err := u.UserDetail()
	if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
		return formdata.UserInfo{}, fmt.Errorf("服务器错误 >>%v", err)
	}
	if data.LoginType == "0" {
		//密码登录  //判断密码
		if !pkg.ComparePwd(detail.Password, data.Password) {
			fmt.Println(detail.Password + "-----" + data.Password)
			return formdata.UserInfo{}, fmt.Errorf("手机号或密码错误 >>%v", data.Password)
		}
	} else {
		//短信验证码登录  //获取缓存放验证码
		key := "phone_:" + data.Phone + "_type" + data.CodeType
		codeVal, err := redis.GetRedisVal(key)
		if err != nil {
			return formdata.UserInfo{}, err
		}
		fmt.Println("短信验证码", codeVal)
		if codeVal != data.Code {
			fmt.Println(codeVal + "-----" + data.Code)
			return formdata.UserInfo{}, errors.New("短信验证失败")
		}
		fmt.Println("短信验证验证码成功")
	}
	//生成token
	token, err := pkg.GetJwtToken(strconv.Itoa(int(detail.ID)))
	if err != nil {
		return formdata.UserInfo{}, err
	}
	userInfo := formdata.UserInfo{
		Name:     detail.Name,
		Phone:    detail.Phone,
		Img:      detail.Img,
		Gender:   detail.Gender,
		Birthday: detail.Birthday,
		Status:   detail.Status,
		Token:    token,
	}
	return userInfo, nil
}

// 修改用户密码
func UpdatePasswordByUserID(data formdata.UpdateDara, userID int64) error {
	//密码加密
	pwd, _ := pkg.GetPwd(data.Password)
	u := user.User{
		Model:    gorm.Model{ID: uint(userID)},
		Phone:    data.Phone,
		Password: pwd,
	}
	fmt.Println("用户id ", userID)
	fmt.Println("密码", pwd)
	//判断验证码
	key := "phone_:" + data.Phone + "_type" + data.CodeType
	codeVal, err := redis.GetRedisVal(key)
	if err != nil {
		return err
	}
	if codeVal != data.Code {
		fmt.Println(codeVal + "-----" + data.Code)
		return errors.New("短信验证失败")
	}
	fmt.Println("短信验证验证码成功")
	return u.UpdateDara()
}

// 注册
func Register(data formdata.UserRegister) (string, error) {
	//手机号格式效验
	bools := pkg.MobileTypeBook(data.Phone)
	if !bools {
		return "", errors.New("手机号格式效验错误")
	}
	//随机图片
	urlRand, err := pkg.GetRandomAvatarURL()
	if err != nil {
		return "", fmt.Errorf("生成随机索引头像失败: %v", err)
	}
	//随机昵称
	nickname, err := pkg.GetRandomNickname()
	if err != nil {
		return "", fmt.Errorf("获取随机昵称失败: %v", err)
	}
	//密码加密
	mdPwd, _ := pkg.GetPwd(data.Password)
	u := user.User{
		Name:     nickname,
		Phone:    data.Phone,
		Password: mdPwd,
		Img:      urlRand,
	}
	//查询用户手机号是否存在
	detail, err := u.UserDetail()
	if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
		return "", fmt.Errorf("服务器错误 >>%v", err)
	}
	if detail.ID != 0 {
		return "", errors.New("该手机号已注册") // 如果用户已存在，返回错误
	}
	r, err := u.Create()
	if err != nil {
		return "", errors.New("注册失败")
	}
	//生成token
	return pkg.GetJwtToken(strconv.Itoa(int(r.ID)))
}
